﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Windows.Forms;

namespace Admx_Generator
{
    public partial class FrmAddNamespace : Form
    {
        private System.Resources.ResourceManager resMan = new System.Resources.ResourceManager("Admx_Generator.Localization.LocalizedStrings", typeof(FrmAddNamespace).Assembly);
        private List<Namespace> _namespaces;
        private Namespace _selectedNamespace = null;

        internal FrmAddNamespace(List<Namespace> namespaces)
        {
            InitializeComponent();
            this._namespaces = namespaces;
            this.cmbBxNamespaces.Items.AddRange(namespaces.ToArray());            
        }

        #region (Internal Properties)

        /// <summary>
        /// Allow to get the Namespace designated by the user to be added.
        /// </summary>
        internal Namespace Namespace { get { return this._selectedNamespace; } }

        #endregion (Internal Properties)

        #region (Private Methods)

        private void ValidateData()
        {
            btnOk.Enabled = (this.cmbBxNamespaces.SelectedIndex != -1) || (!string.IsNullOrEmpty(txtBxFilename.Text) && (System.IO.File.Exists(txtBxFilename.Text)));
        }

        private void ExtractNamespaceFromAdmxFile(string filename)
        {
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filename);
            this.cmbBxNamespaces.SelectedIndex = -1;
            this.txtBxNamespace.Text = String.Empty;

            if (fileInfo.Exists)
            {
                try
                {
                    XDocument xDoc = XDocument.Load(filename);
                    XNamespace ns = xDoc.Root.GetDefaultNamespace();
                    XElement target = xDoc.Descendants(ns + "target").ToList<XElement>()[0];
                    XAttribute namespaceAttribute = target.Attribute("namespace");
                    this.txtBxNamespace.Text = namespaceAttribute.Value;
                }
                catch (Exception) { }
            }
        }

        /// <summary>
        /// Returns a localized string depending of the current culture.
        /// </summary>
        /// <param name="unlocalizedString">string to localized.</param>
        /// <returns>the localized string.</returns>
        protected string GetLocalizedString(string unlocalizedString)
        {
            string result = string.Empty;

            try
            {
                result = resMan.GetString(unlocalizedString);
                if (!string.IsNullOrEmpty(result))
                    return result;
            }
            catch (Exception) { }

            return "Missing_Localized_String_For(" + ((unlocalizedString != null) ? unlocalizedString : "null") + ")";
        }

        #endregion (Private Methods)

        #region (UI Managment)

        private void txtBxNamespace_TextChanged(object sender, EventArgs e)
        {
            ValidateData();
        }

        private void txtBxFilename_TextChanged(object sender, EventArgs e)
        {
            ValidateData();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "Admx Files (*.Admx)|*.admx";
            openFile.InitialDirectory = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\PolicyDefinitions");
            openFile.CheckFileExists = true;
            openFile.CheckPathExists = true;

            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK && openFile.FileName.EndsWith(".admx", StringComparison.InvariantCultureIgnoreCase))
            {
                this.txtBxNamespace.Text = string.Empty;
                this.txtBxFilename.Text = openFile.FileName;
                try
                {
                    this._selectedNamespace = new Namespace(openFile.FileName);
                    this.ExtractNamespaceFromAdmxFile(txtBxFilename.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this.GetLocalizedString("AnErrorOccurredWhileLoadAdmxFile") + "\r\n" + ex.Message);
                    this.txtBxFilename.Text = String.Empty;
                }
            }
            ValidateData();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.txtBxNamespace.Text = string.Empty;
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void cmbBxNamespaces_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(this.cmbBxNamespaces.SelectedIndex != -1 && this.cmbBxNamespaces.SelectedItem != null)
            {
                this.txtBxFilename.Text = String.Empty;
                this.txtBxNamespace.Text = String.Empty;
                this._selectedNamespace = this._namespaces[this.cmbBxNamespaces.SelectedIndex];
                ValidateData();
            }
        }


        #endregion (UI Managment)

    }
}
